<template>
  <div class="article-container">
    <div class="daohang">报修列表</div>
    <button @click="navigateToRoute('/new-repair')" type="button" title="进入报修页面"
      class="btn btn-success btn-lg ft18 pull-right mar-t15 mar-t15 baoxiubtn">
      <img src="../assets/img/icon-repair.png">&nbsp;&nbsp;我要报修</button>

    <el-select v-model="form.repairState" placeholder="请选择状态" class="custom-select" clearable
      @change="handleStatusChange">
      <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" style="width: 82%">
      <el-tab-pane label="未删除" name="undeleted">
        <!-- 数据表格 -->
        <el-table :data="allData" empty-text="暂无数据" style="width: 1200px">
          <el-table-column fixed prop="repairNum" label="编号" style="width: 10%" />
          <el-table-column prop="repairInfo" label="区域" style="width: 10%" />
          <el-table-column prop="repairType" label="项目" style="width: 10%" />
          <el-table-column prop="repairUserName" label="报修人" style="width: 10%" />
          <el-table-column prop="appointmentTime" label="预约时间" style="width: 10%" />
          <el-table-column prop="repairPersonName" label="受理人" style="width: 10%" />
          <el-table-column prop="repairTakeTime" label="受理用时" style="width: 10%" />
          <el-table-column prop="state" label="状态" style="width: 10%" />
          <el-table-column fixed="right" label="操作" style="width: 20%">
            <template #default="scope">
              <el-button link type="primary" size="small"
                @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                查看详情
              </el-button>
              <el-button v-if="scope.row.repairState === 0" link type="danger" size="small"
                @click="openCancelDialog(scope.row.repairNum)">
                取消
              </el-button>
              <el-button v-if="[3, 4, 5].includes(scope.row.repairState)" link type="danger" size="small"
                @click="openDeleteDialog(scope.row.repairNum)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"></el-pagination>
      </el-tab-pane>
      <el-tab-pane label="已删除" name="deleted">
        <!-- 数据表格 -->
        <el-table :data="allDataDeleted" empty-text="暂无数据" style="width: 1200px">
          <el-table-column fixed prop="repairNum" label="编号" style="width: 10%" />
          <el-table-column prop="repairInfo" label="区域" style="width: 10%" />
          <el-table-column prop="repairType" label="项目" style="width: 10%" />
          <el-table-column prop="repairUserName" label="报修人" style="width: 10%" />
          <el-table-column prop="appointmentTime" label="预约时间" style="width: 10%" />
          <el-table-column prop="repairPersonName" label="受理人" style="width: 10%" />
          <el-table-column prop="repairTakeTime" label="受理用时" style="width: 10%" />
          <el-table-column prop="state" label="状态" style="width: 10%" />
          <el-table-column fixed="right" label="操作" style="width: 20%">
            <template #default="scope">
              <el-button link type="primary" size="small"
                @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination @size-change="handleSizeChangeDeleted" @current-change="handleCurrentChangeDeleted"
          :current-page="currentPageDeleted" :page-sizes="[5, 10, 20]" :page-size="pageSizeDeleted"
          layout="total, sizes, prev, pager, next, jumper" :total="totalItemsDeleted"></el-pagination>
      </el-tab-pane>
    </el-tabs>

    <!-- 取消弹窗 -->
    <el-dialog title="取消维修单" v-model="cancelDialogVisible" width="30%">
      <el-form :model="cancelForm" label-width="100px">
        <el-form-item label="取消原因">
          <el-input v-model="cancelForm.reason" type="textarea" :rows="4" placeholder="请输入取消原因"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCancel">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog title="删除维修单" v-model="deleteDialogVisible" width="30%">
      <span>确定要删除维修单 {{ currentRepairNum }} 吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRow,
  ElCol,
  ElButton,
  ElDatePicker,
  ElUpload,
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElDialog,
  ElTabs,
  ElTabPane,
  ElTable,
  ElTableColumn,
  ElPagination,
} from "element-plus";
import axios from 'axios';

export default {
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
    ElButton,
    ElDatePicker,
    ElUpload,
    ElBreadcrumb,
    ElBreadcrumbItem,
    ElDialog,
    ElTabs,
    ElTabPane,
    ElTable,
    ElTableColumn,
    ElPagination,
  },
  data() {
    return {
      form: {
        repairState: ''
      },
      statusOptions: [
        {value: 1, label: '已分配'},
        {value: 2, label: '维修中'},
        {value: 3, label: '维修完成'},
        {value: 4, label: '已驳回'},
        {value: 5, label: '已取消'},
        {value: 0, label: '待审核'}
      ],
      area: '',
      project: '',
      unit: '',
      searchContent: '',
      searchContact: '',
      areaOptions: [],
      projectOptions: [],
      unitOptions: [],
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      allData: [],
      currentData: [],
      userAllData: [],
      userCurrentData: [],
      userRepairState: '', // 维修工单的状态
      userDeleted: 0, // 删除标志（0: 未删除, 1: 已删除）
      // 已删除数据的分页相关数据
      currentPageDeleted: 1,
      pageSizeDeleted: 10,
      totalItemsDeleted: 0,
      allDataDeleted: [],
      deletedData: [],
      cancelDialogVisible: false,
      cancelForm: {
        reason: ''
      },
      deleteDialogVisible: false,
      currentRepairNum: '',
      activeTab: 'undeleted'
    };
  },
  mounted() {
    this.fetchRepairData();
  },
  methods: {
    navigateToRoute(route) {
      this.$router.push(route);
    },
    async fetchRepairData() {
      const deleted = this.activeTab === 'undeleted' ? 0 : 1;
      const pageNum = this.activeTab === 'undeleted' ? this.currentPage : this.currentPageDeleted;
      const pageSize = this.activeTab === 'undeleted' ? this.pageSize : this.pageSizeDeleted;

      try {
        const response = await axios.post('/repaircenter/repair/selectRepairByUserId', {
          pageNum,
          pageSize,
          repairState: this.form.repairState,
          deleted
        });
        if (response.data.code === 200) {
          if (deleted === 0) {
            console.log(response.data.data.list);
            this.allData = response.data.data.list;
            this.totalItems = response.data.data.total;
            this.updateCurrentData();
          } else {
            this.allDataDeleted = response.data.data.list;
            this.totalItemsDeleted = response.data.data.total;
            this.updateDeletedData();
          }
        } else {
          this.$message.error("查询维修记录失败");
        }
      } catch (error) {
        console.error('查询维修记录失败', error);
        this.$message.error("查询维修记录失败");
      }
    },
    updateCurrentData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.currentData = this.allData.slice(start, end);
    },
    updateDeletedData() {
      const start = (this.currentPageDeleted - 1) * this.pageSizeDeleted;
      const end = start + this.pageSizeDeleted;
      this.deletedData = this.allDataDeleted.slice(start, end);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleSizeChangeDeleted(val) {
      this.pageSizeDeleted = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleCurrentChangeDeleted(val) {
      this.currentPageDeleted = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleStatusChange(val) {
      this.form.repairState = val;
      this.fetchRepairData(); // 重新获取数据
    },
    handleTabChange({props}) {
      this.activeTab = props.name;
      this.fetchRepairData(); // 重新获取数据
    },
    selectRepairById(repairId, repairNum) {
      this.$router.push({ name: 'RepairInfo', params: { id: repairId, num: repairNum } });
    },
    openCancelDialog(repairNum) {
      this.cancelDialogVisible = true;
      this.cancelForm.reason = ''; // 清空上次输入的取消原因
      this.currentRepairNum = repairNum; // 存储当前维修单ID
    },
    async confirmCancel() {
      if (!this.cancelForm.reason) {
        this.$message.warning('请输入取消原因');
        return;
      }
      try {
        const response = await axios.put('/repaircenter/repair/cancelRepair', {
          repairNum: this.currentRepairNum,
          description: this.cancelForm.reason
        });
        console.log('取消结果', response.data);
        this.$message.success("取消成功");
        this.fetchRepairData(); // 刷新列表
        this.cancelDialogVisible = false;
      } catch (error) {
        console.error('取消失败', error);
        this.$message.error("取消失败");
      }
    },
    openDeleteDialog(repairNum) {
      this.deleteDialogVisible = true;
      this.currentRepairNum = repairNum; // 存储当前维修单ID
    },
    async confirmDelete() {
      try {
        const response = await axios.delete('/repaircenter/repair/deleteRepair', {
          params: {
            repairNum: this.currentRepairNum
          }
        });
        console.log('删除结果', response.data);
        this.$message.success("删除成功");
        this.fetchRepairData(); // 刷新列表
        this.deleteDialogVisible = false;
      } catch (error) {
        console.error('删除失败', error);
        this.$message.error("删除失败");
      }
    }
  }
};
</script>

<style scoped>
.repair-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.el-upload__tip {
  line-height: 1.2;
}

.article-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  margin-top: 110px;
}

.daohang {
  width: 83%;
  text-align: left;
  border-bottom: 1px solid #00000017;
  background: url(../assets/img/icon-location-blue.png) no-repeat 0 8px;
  background-position: 0px 0px; /* 调整位置 */
  padding-left: 20px;
}

.custom-select {
  width: 200px; /* 根据需要调整宽度 */
}
.baoxiubtn{
  margin-left: 73%;
  margin-bottom: 15px;
}
</style>
